<!-- src/components/AuditDialog.vue -->
<template>
  <el-dialog :title="title" v-model="visible" width="480px" :close-on-click-modal="false" @close="handleClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <!-- 审核结果 -->
      <el-form-item label="审核结果" prop="auditStatus">
        <el-radio-group v-model="form.auditStatus" @change="changeStatus">
          <el-radio :label="1">通过</el-radio>
          <el-radio :label="2">驳回</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 驳回方式 -> 映射 auditType -->
      <el-form-item v-if="form.auditStatus === 2" label="驳回方式" prop="auditType">
        <el-select v-model="form.auditType" placeholder="请选择">
          <el-option label="信息错误，打款错误" :value="3" />
          <el-option label="信息错误，打款正确" :value="1" />
          <el-option label="信息正确，打款错误" :value="2" />
        </el-select>
      </el-form-item>

      <!-- 驳回原因 -->
      <el-form-item v-if="form.auditStatus === 2" label="驳回原因" prop="auditReason">
        <el-input v-model="form.auditReason" type="textarea" :rows="3" maxlength="200" show-word-limit placeholder="请输入驳回原因" />
      </el-form-item>

      <!-- 通过时：上传附件 -->
      <el-form-item v-if="form.auditStatus === 1" label="审核附件">
        <el-upload ref="uploadRef" action="#" :limit="1" :file-list="fileList" :before-upload="beforeUpload" :http-request="uploadFile" accept=".pdf,.png,.jpg,.jpeg">
          <el-button type="primary">选择文件</el-button>
          <template #tip>
            <div class="el-upload__tip">支持 PDF/PNG/JPG/JPEG，大小 ≤5MB</div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="loading" @click="submit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick } from "vue";
import { ElMessage } from "element-plus";
import type { FormInstance, UploadRequestOptions } from "element-plus";
import baseService from "@/service/baseService";

interface Emits {
  (e: "success"): void;
}
const emit = defineEmits<Emits>();

const formRef = ref<FormInstance>();
const visible = ref(false);
const url = ref(String);
const loading = ref(false);
const title = ref("企业认证审核");

const fileList = ref<any[]>([]);
let currentFile: File | null = null;

const form = reactive({
  id: "",
  auditStatus: 1,
  auditType: 1, // 驳回时 1|2|3
  auditReason: "", // 驳回原因
  auditImage: "" // 通过时附件 url
});

const rules = {
  auditStatus: [{ required: true, message: "请选择结果", trigger: "change" }],
  auditType: [{ required: true, message: "请选择驳回方式", trigger: "change" }],
  auditReason: [{ required: true, message: "请输入驳回原因", trigger: "blur" }]
};

/* 打开弹窗 */
function open(row: any) {
  form.id = row.id;
  visible.value = true;
  nextTick(() => formRef.value?.resetFields());
}

/* 关闭弹窗 */
function handleClose() {
  visible.value = false;
  fileList.value = [];
  currentFile = null;
  formRef.value?.resetFields();
}

/* 审核结果切换 */
function changeStatus(val: number) {
  if (val === 1) {
    form.auditType = 1;
    form.auditReason = "";
  } else if (val === 2) {
    // 新增：驳回时默认选中“信息错误，打款错误”
    form.auditType = 3;
    form.auditReason = "";
  }
}

/* 上传前校验 */
function beforeUpload(file: File) {
  const allow = ["image/png", "image/jpeg", "application/pdf"];
  const ok = allow.includes(file.type) && file.size / 1024 / 1024 <= 5;
  if (!ok) ElMessage.error("格式或大小不符");
  return ok;
}

/* 手动上传：先调 /upload 拿到 url */
async function uploadFile({ file }: UploadRequestOptions) {
  const fd = new FormData();
  fd.append("file", file);
  try {
    const { url } = await baseService.post("/sys/oss/upload", fd, {
      headers: { "Content-Type": "multipart/form-data" }
    });
    // const url = res.url;
    form.auditImage = url;
    fileList.value = [{ name: file.name, url: url }];
  } catch (e: any) {
    ElMessage.error(e?.message || "上传失败");
    fileList.value = [];
  }
}

/* 提交审核 */
async function submit() {
  await formRef.value?.validate();
  loading.value = true;

  /* 构建 body */
  const body = {
    id: form.id,
    auditStatus: String(form.auditStatus),
    auditImage: form.auditImage,
    auditType: "",
    auditReason: ""
  };
  if (form.auditStatus === 2) {
    body.auditReason = form.auditReason;
    body.auditType = String(form.auditType); // 1|2|3
  }

  try {
    await baseService.post("/noc/authcompanyaudit/audit", body);
    ElMessage.success("审核完成");
    handleClose();
    emit("success");
  } finally {
    loading.value = false;
  }
}

defineExpose({ open });
</script>
